package com.itheima.service.Impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MessageDao;
import com.itheima.entity.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.MessageDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Message;
import com.itheima.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = MessageService.class)
@Transactional
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageDao messageDao;


    public PageResult selectByCondition(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());

        List<Map> list = messageDao.selectByCondition(queryPageBean.getQueryString());
        PageInfo<Map> pageInfo = new PageInfo<>(list);

        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    public void deleteById(Integer id) {
        messageDao.deleteById(id);
    }

    @Override
    public Result savaMessage(Map<String, String> map) {


        String name = map.get("name");
        String info = map.get("message");
        Message message = new Message(name, info, new Date());

        try {
            messageDao.saveMessage(message);
            return new Result(true, "留言提交成功，感谢亲的留言！");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "一不小心就提交失败了！");
        }

    }

    @Override
    public List<Map<String, Object>> findAllMessages() {
        List<Map<String, Object>> messages = messageDao.findAllMessages();
        for (Map<String, Object> message : messages) {
            String memberName = message.get("member_name").toString();
            String substring = memberName.substring(0, 1);
            for (int i = 0; i < memberName.length() - 1; i++) {
                substring += "*";
            }
            message.put("member_name", substring);
        }
        return messages;
    }
}
